import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/constants.dart';
import '../../data/models/puzzle_game.dart';
import '../../data/models/puzzle_piece.dart';
import '../../data/services/puzzle_generator.dart';
import '../../data/services/image_processor.dart';

/// 游戏视图模型
class GameViewModel extends ChangeNotifier {
  // =================== 依赖注入 ===================
  final PuzzleGeneratorService _puzzleGenerator = PuzzleGeneratorService();
  final ImageProcessorService _imageProcessor = ImageProcessorService();
  
  // =================== 私有状态 ===================
  PuzzleGame _currentGame = PuzzleGame.initial();
  bool _isLoading = false;
  String? _errorMessage;
  Timer? _gameTimer;
  Duration _elapsedTime = Duration.zero;
  
  // 选中状态追踪
  int? _selectedPieceId;
  
  // 性能优化：减少不必要的通知
  final bool _shouldNotifyListeners = true;
  
  // =================== 公共属性（只读） ===================
  
  /// 当前游戏状态
  PuzzleGame get currentGame => _currentGame;
  
  /// 是否正在加载
  bool get isLoading => _isLoading;
  
  /// 错误信息
  String? get errorMessage => _errorMessage;
  
  /// 已用时间
  Duration get elapsedTime => _elapsedTime;
  
  /// 格式化的已用时间
  String get formattedElapsedTime {
    final minutes = _elapsedTime.inMinutes;
    final seconds = _elapsedTime.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
  
  /// 当前选中的拼图块ID
  int? get selectedPieceId => _selectedPieceId;
  
  /// 是否有拼图块被选中
  bool get hasSelectedPiece => _selectedPieceId != null;
  
  /// 游戏统计信息
  Map<String, dynamic> get gameStats => {
    'difficulty': _currentGame.difficulty.displayName,
    'totalPieces': _currentGame.totalPieces,
    'placedPieces': _currentGame.correctlyPlacedCount,
    'completion': '${(_currentGame.completionPercentage * 100).toStringAsFixed(1)}%',
    'moves': _currentGame.moveCount,
    'time': formattedElapsedTime,
    'isCompleted': _currentGame.isCompleted,
  };
  
  // =================== 游戏生命周期管理 ===================
  
  /// 初始化新游戏
  Future<void> initializeGame({
    required String imagePath,
    required DifficultyLevel difficulty,
  }) async {
    try {
      debugPrint('=== GameViewModel 调试信息 ===');
      debugPrint('开始初始化游戏');
      debugPrint('图片路径: $imagePath');
      debugPrint('难度: ${difficulty.displayName}');
      debugPrint('=============================');
      
      _setLoading(true);
      _clearError();
      
      // 第一步：停止当前游戏
      await stopGame();
      
      // 第二步：预处理图片
      debugPrint('开始预处理图片...');
      await _imageProcessor.preprocessImageForPuzzle(imagePath);
      debugPrint('图片预处理完成');
      
      // 第三步：生成拼图游戏
      debugPrint('开始生成拼图...');
      final game = await _puzzleGenerator.generatePuzzleGame(
        imagePath: imagePath,
        difficulty: difficulty,
      );
      debugPrint('拼图生成完成，拼图块数量: ${game.pieces.length}');
      
      // 第四步：更新状态
      _currentGame = game.startGame();
      _elapsedTime = Duration.zero;
      _selectedPieceId = null;
      
      debugPrint('游戏状态更新完成');
      debugPrint('当前游戏拼图块数量: ${_currentGame.pieces.length}');
      
      // 第五步：开始计时
      _startGameTimer();
      
      debugPrint('✅ [GameViewModel] 游戏初始化完成');
      
    } catch (e) {
      debugPrint('❌ 游戏初始化失败: $e');
      debugPrint('错误详情: ${e.toString()}');
      _setError('游戏初始化失败: $e');
    } finally {
      _setLoading(false);
    }
  }
  
  /// 开始游戏计时器
  void _startGameTimer() {
    _gameTimer?.cancel();
    _gameTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_currentGame.isPlaying) {
        _elapsedTime = _elapsedTime + const Duration(seconds: 1);
        _safeNotifyListeners();
      }
    });
  }
  
  /// 停止游戏
  Future<void> stopGame() async {
    _gameTimer?.cancel();
    _gameTimer = null;
    
    if (_currentGame.status == GameStatus.playing) {
      _currentGame = _currentGame.pauseGame();
      _safeNotifyListeners();
    }
  }
  
  /// 暂停游戏
  void pauseGame() {
    if (_currentGame.isPlaying) {
      _currentGame = _currentGame.pauseGame();
      _gameTimer?.cancel();
      debugPrint('⏸️ [GameViewModel] 游戏已暂停');
      _safeNotifyListeners();
    }
  }
  
  /// 恢复游戏
  void resumeGame() {
    if (_currentGame.isPaused) {
      _currentGame = _currentGame.resumeGame();
      _startGameTimer();
      debugPrint('▶️ [GameViewModel] 游戏已恢复');
      _safeNotifyListeners();
    }
  }
  
  /// 重置游戏
  Future<void> resetGame() async {
    if (_currentGame.imagePath.isEmpty) return;
    
    await initializeGame(
      imagePath: _currentGame.imagePath,
      difficulty: _currentGame.difficulty,
    );
  }
  
  /// 重新打乱拼图
  void shufflePuzzle() {
    if (!_currentGame.isPlaying) return;
    
    debugPrint('🔀 [GameViewModel] 重新打乱拼图');
    
    final shuffledPieces = _puzzleGenerator.reshufflePieces(_currentGame.pieces);
    _currentGame = _currentGame.copyWith(
      pieces: shuffledPieces,
      moveCount: _currentGame.moveCount + 1,
    );
    
    _safeNotifyListeners();
  }
  
  // =================== 点击交互处理 ===================
  
  /// 处理拼图块点击
  void handlePieceClick(int pieceId) {
    if (!_currentGame.isPlaying) return;
    
    debugPrint('点击拼图块: $pieceId');
    
    if (_selectedPieceId == null) {
      // 选中这个拼图块
      _selectPiece(pieceId);
    } else if (_selectedPieceId == pieceId) {
      // 取消选中
      _deselectPiece();
    } else {
      // 交换两个拼图块
      _swapPieces(_selectedPieceId!, pieceId);
    }
  }
  
  /// 处理空白格子点击
  void handleEmptyGridClick(int row, int col) {
    if (!_currentGame.isPlaying || _selectedPieceId == null) return;
    
    debugPrint('点击空白格子: ($row, $col)');
    
    // 检查目标位置是否真的为空
    if (_currentGame.isPositionOccupied(row, col)) {
      debugPrint('位置已被占用');
      return;
    }
    
    // 移动选中的拼图块到空白位置
    _movePieceToPosition(_selectedPieceId!, row, col);
  }
  
  /// 选中拼图块
  void _selectPiece(int pieceId) {
    debugPrint('选中拼图块: $pieceId');
    _selectedPieceId = pieceId;
    
    final updatedPieces = _currentGame.pieces.map((piece) {
      return piece.copyWith(isSelected: piece.id == pieceId);
    }).toList();
    
    _currentGame = _currentGame.copyWith(pieces: updatedPieces);
    _safeNotifyListeners();
  }
  
  /// 取消选中
  void _deselectPiece() {
    debugPrint('取消选中');
    _selectedPieceId = null;
    
    final updatedPieces = _currentGame.pieces.map((piece) {
      return piece.copyWith(isSelected: false);
    }).toList();
    
    _currentGame = _currentGame.copyWith(pieces: updatedPieces);
    _safeNotifyListeners();
  }
  
  /// 移动拼图块到指定位置
  void _movePieceToPosition(int pieceId, int targetRow, int targetCol) {
    debugPrint('移动拼图块 $pieceId 到位置 ($targetRow, $targetCol)');
    
    final updatedPieces = _currentGame.pieces.map((piece) {
      if (piece.id == pieceId) {
        return piece.placeAt(targetRow, targetCol).copyWith(isSelected: false);
      }
      return piece.copyWith(isSelected: false);
    }).toList();
    
    _selectedPieceId = null;
    _currentGame = _currentGame.copyWith(pieces: updatedPieces).incrementMoveCount();
    
    _checkGameCompletion();
    _safeNotifyListeners();
  }
  
  /// 交换两个拼图块的位置
  void _swapPieces(int pieceId1, int pieceId2) {
    debugPrint('交换拼图块 $pieceId1 和 $pieceId2');
    
    final piece1 = _currentGame.pieces.firstWhere((p) => p.id == pieceId1);
    final piece2 = _currentGame.pieces.firstWhere((p) => p.id == pieceId2);
    
    final updatedPieces = _currentGame.pieces.map((piece) {
      if (piece.id == pieceId1) {
        // piece1 移动到 piece2 的位置
        if (piece2.isInGameArea) {
          return piece.placeAt(piece2.currentRow, piece2.currentCol)
              .copyWith(isSelected: false);
        } else {
          return piece.moveToScatterArea(piece2.position)
              .copyWith(isSelected: false);
        }
      } else if (piece.id == pieceId2) {
        // piece2 移动到 piece1 的位置
        if (piece1.isInGameArea) {
          return piece.placeAt(piece1.currentRow, piece1.currentCol)
              .copyWith(isSelected: false);
        } else {
          return piece.moveToScatterArea(piece1.position)
              .copyWith(isSelected: false);
        }
      }
      return piece.copyWith(isSelected: false);
    }).toList();
    
    _selectedPieceId = null;
    _currentGame = _currentGame.copyWith(pieces: updatedPieces).incrementMoveCount();
    
    _checkGameCompletion();
    _safeNotifyListeners();
  }
  
  /// 检查游戏完成
  void _checkGameCompletion() {
    if (_currentGame.isCompleted) {
      debugPrint('🎉 [GameViewModel] 拼图完成！');
      
      // 停止计时器
      _gameTimer?.cancel();
      
      // 更新游戏状态为完成
      _currentGame = _currentGame.completeGame();
      
      _safeNotifyListeners();
    }
  }
  
  // =================== 辅助功能 ===================
  
  /// 获取提示
  PuzzlePiece? getHint() {
    if (!_currentGame.isPlaying) return null;
    
    return _puzzleGenerator.getNextHint(_currentGame.pieces);
  }
  
  /// 自动解决拼图（调试功能）
  void autoSolve() {
    if (!_currentGame.isPlaying) return;
    
    debugPrint('🤖 [GameViewModel] 自动解决拼图');
    
    final solvedPieces = _puzzleGenerator.autoSolvePuzzle(_currentGame.pieces);
    _currentGame = _currentGame.copyWith(pieces: solvedPieces);
    
    _checkGameCompletion();
  }
  
  /// 切换难度
  Future<void> changeDifficulty(DifficultyLevel newDifficulty) async {
    if (_currentGame.imagePath.isEmpty) return;
    
    await initializeGame(
      imagePath: _currentGame.imagePath,
      difficulty: newDifficulty,
    );
  }
  
  /// 切换图片
  Future<void> changeImage(String imagePath) async {
    await initializeGame(
      imagePath: imagePath,
      difficulty: _currentGame.difficulty,
    );
  }
  
  // =================== 状态管理辅助方法 ===================
  
  void _setLoading(bool loading) {
    if (_isLoading != loading) {
      _isLoading = loading;
      if (loading) _clearError();
      _safeNotifyListeners();
    }
  }
  
  void _setError(String error) {
    _errorMessage = error;
    _setLoading(false);
    _safeNotifyListeners();
  }
  
  void _clearError() {
    if (_errorMessage != null) {
      _errorMessage = null;
      _safeNotifyListeners();
    }
  }
  
  /// 安全的通知监听器（避免重复通知）
  void _safeNotifyListeners() {
    if (_shouldNotifyListeners && hasListeners) {
      notifyListeners();
    }
  }
  
  // =================== 生命周期管理 ===================
  
  @override
  void dispose() {
    debugPrint('🗑️ [GameViewModel] 清理资源');
    
    _gameTimer?.cancel();
    
    super.dispose();
  }
  
  // =================== 调试和监控 ===================
  
  /// 获取调试信息
  Map<String, dynamic> getDebugInfo() {
    return {
      'gameStatus': _currentGame.status.displayName,
      'isLoading': _isLoading,
      'hasError': _errorMessage != null,
      'elapsedTime': formattedElapsedTime,
      'selectedPieceId': _selectedPieceId,
      'gameStats': gameStats,
      'memoryInfo': {
        'hasListeners': hasListeners,
        'shouldNotify': _shouldNotifyListeners,
      }
    };
  }
}

/// 扩展方法
extension GameViewModelExtensions on GameViewModel {
  /// 是否可以开始游戏
  bool get canStartGame => !isLoading && errorMessage == null;
  
  /// 是否可以暂停
  bool get canPause => currentGame.isPlaying && !hasSelectedPiece;
  
  /// 是否可以重置
  bool get canReset => currentGame.status != GameStatus.initial;
  
  /// 获取完成度百分比
  int get completionPercentage => (currentGame.completionPercentage * 100).round();
  
  /// 是否是新手难度
  bool get isEasyMode => currentGame.difficulty == DifficultyLevel.easy;
  
  /// 获取游戏评级
  String get gameRating {
    if (!currentGame.isCompleted) return '进行中';
    
    final moves = currentGame.moveCount;
    final time = elapsedTime.inMinutes;
    
    if (moves < currentGame.totalPieces * 2 && time < 5) return '完美';
    if (moves < currentGame.totalPieces * 3 && time < 10) return '优秀';
    if (moves < currentGame.totalPieces * 5 && time < 20) return '良好';
    return '完成';
  }
}
